include Gosu

class UITextField < UIMenuItem
  attr_accessor :max_chars
  
  def initialize(window, delegate, text = "")
    super(window, delegate, text)
    @clears_on_begin_editing = false
    @field_image = window.images["../3d_renders/text_field.png"]
    @cursor_image = window.images["../3d_renders/text_cursor.png"]
    @text_x, @text_y = 0, 0 # just initializing these
    @active = false # not being edited
    @t_color = 0xff000000 # black text color
    @cursor_color = Color.new(0xffffffff)
    @cursor_factor = 1.0 # just to initialize
    @max_chars = 100
  end

  def update(x, y, width, height, mouse_x, mouse_y)
    # calculate dimensions of background image before drawing.
    # also determine whether the mouse is hovering over valid content.
    super # sets @x, @y, @width, @height, and @color
    border_x = width.to_f / 10
    border_y = height.to_f / 8
    @image_x, @image_y = @x + border_x, @y + border_y
    @image_w, @image_h = @width - 2*border_x, @height - 2*border_y
    @text_x = @image_x + @image_w.to_f / 8
    @text_y = @image_y + @image_h.to_f / 4
    @cursor_factor = @image_h.to_f/60.0 # match the cursor size to the field
    @cursor_color.alpha = (255.0 * Math.sin(Gosu.milliseconds/300.0)).to_i.abs
    return if @state == :disabled

    # update text if active
    if @active
      if @window.text_input.text.length > @max_chars
        @window.text_input.text = @window.text_input.text.chop
      end
      @text = @window.text_input.text
    end
    #ensure the button color stays normal unless mouse_over gets called.
    if mouse_x >= @image_x and mouse_x <= @image_x + @image_w and
      mouse_y >= @image_y and mouse_y <= @image_y + @image_h
        mouse_over
    else
      @state = :static
    end
  end

  def draw
    @field_image.draw_as_quad(@image_x, @image_y, @color,
                        @image_x + @image_w, @image_y, @color,
                        @image_x + @image_w, @image_y + @image_h, @color,
                        @image_x, @image_y + @image_h, @color,
                        ZOrder::BUTTON)
    @font.draw_rel(@text, @text_x, @text_y, ZOrder::TEXT, 
                   0.0, 0.0, 1, 1, @t_color)
    if @active
      @cursor_image.draw(@text_x + @font.text_width(@text) + 3, @text_y, 
                         ZOrder::TEXT, @cursor_factor, @cursor_factor,
                         @cursor_color)
    end
  end

  def clicked(left_or_right, mx, my)
    if @state != :hover
      deactivate
      return
    end
    case left_or_right
    when :left
      @selected_sound.play
      if !@active
        activate
      end
    when :right
      # hmmm. Do nothing. But maybe add something later.
    end
  end

  def activate
      @active = true
      @text = "" if @clears_on_begin_editing
      @window.text_input = Gosu::TextInput.new
      @window.text_input.text = @text
  end

  def deactivate
    @active = false
    @window.text_input = nil
  end

end
